<template>
  <DialogBox :title="'创建知识库'" v-model="dialogVisible" width="600" :before-close="closeConfirm">
    <!-- 基本信息  -->
    <BaseForm ref="BaseFormRef" v-if="dialogVisible" />
    <el-form ref="DatasetFormRef" :rules="rules" :model="datasetForm" label-position="top"
      require-asterisk-position="right">
      <!-- 所属分类 -->
      <el-form-item label="所属分类" prop="perType">
        <el-select v-model="datasetForm.perType" placeholder="请选择所属分类">
          <el-option v-for="item in categorizeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="知识库类型" required>
        <el-radio-group v-model="datasetForm.type" class="card__radio" @change="radioChange">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card shadow="never" class="mb-16" :class="datasetForm.type === '0' ? 'active' : ''"
                @click="datasetForm.type = '0'">
                <div class="flex-between">
                  <div class="flex align-center">
                    <img src="@/assets/dataset/icon_document.svg" style="height:36px" alt="" />
                    <div class="pl-10">
                      <p>
                        <el-text>通用型</el-text>
                      </p>
                      <el-text type="info">上传本地文档</el-text>
                    </div>
                  </div>
                  <el-radio value="0" size="large" style="width: 16px"></el-radio>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="never" class="mb-16" :class="datasetForm.type === '1' ? 'active' : ''"
                @click="datasetForm.type = '1'">
                <div class="flex-between">
                  <div class="flex align-center">
                    <img src="@/assets/dataset/icon_web.svg" style="height:36px" alt="" />
                    <div class="pl-10">
                      <p>
                        <el-text>web 站点</el-text>
                      </p>
                      <el-text type="info">同步Web网站文本数据</el-text>
                    </div>
                  </div>
                  <el-radio value="1" size="large" style="width: 16px"></el-radio>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="Web 根地址" prop="sourceUrl" v-if="datasetForm.type === '1'">
        <el-input v-model="datasetForm.sourceUrl" placeholder="请输入 Web 根地址"
          @blur="datasetForm.sourceUrl = datasetForm.sourceUrl.trim()" />
      </el-form-item>
      <el-form-item label="选择器" v-if="datasetForm.type === '1'">
        <el-input v-model="datasetForm.selector" placeholder="默认为 body，可输入 .classname/#idname/tagname"
          @blur="datasetForm.selector = datasetForm.selector.trim()" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button @click.prevent="closeConfirm" :loading="loading">
          取消
        </el-button>
        <el-button type="primary" @click="submitHandle" :loading="loading">
          创建
        </el-button>
      </span>
    </template>
  </DialogBox>
</template>
<script setup lang="ts">
import { isFunction, isEqual, cloneDeep } from 'lodash'
import { ref, watch, reactive } from 'vue'
import { useRouter } from 'vue-router'
import BaseForm from './BaseForm.vue'
import { save1 } from '@/servers/ai/api/zhishiku';
import { MsgSuccess, MsgError, MsgConfirm } from '@/utils/message'

import useStore from '@/stores'
const { dataset } = useStore()

const categorizeOptions = ref<any[]>([])

const emit = defineEmits(['refresh'])

const router = useRouter()
const BaseFormRef = ref()
const DatasetFormRef = ref()

const loading = ref(false)
const dialogVisible = ref<boolean>(false)

const datasetForm = ref<any>({
  type: '0',
  sourceUrl: '',
  selector: '',
  perType: '',
})

const rules = reactive({
  sourceUrl: [
    {
      required: true,
      message: '请输入 Web 根地址',
      trigger: 'blur'
    }
  ],
  perType: [
    {
      required: true,
      message: '请选择分类',
      trigger: 'change'
    }
  ]
})

watch(dialogVisible, (bool) => {
  console.log(bool)
  if (!bool) {
    datasetForm.value = {
      type: '0',
      sourceUrl: '',
      selector: '',
      perType: '',
    }
    DatasetFormRef.value?.clearValidate()
    dialogVisible.value = false
  }
})

const open = async () => {
  dialogVisible.value = true

  // 获取分类
  const options: any = await dataset.getCategorizeOptions()
  categorizeOptions.value = [...options]
}

const submitHandle = async () => {
  try {
    if (!(await BaseFormRef.value?.validate())) {
      return false;
    }

    const valid = await DatasetFormRef.value.validate();
    if (!valid) {
      return false;
    }

    loading.value = true;

    const obj = {
      ...BaseFormRef.value.form,
      ...(datasetForm.value.type === '0' ? { type: datasetForm.value.type, perType: datasetForm.value.perType } : datasetForm.value),
      description: BaseFormRef.value.form.desc
    };

    const res: any = await save1(obj);
    if (res.data.isSuccess) {
      MsgSuccess('创建成功');
      dialogVisible.value = false;
      emit('refresh');
    }
  } catch (e: any) {
    MsgError(e.response?.data?.msg || '请求失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
function radioChange() {
  datasetForm.value.sourceUrl = ''
  datasetForm.value.selector = ''
}

const initFormData: any = ref({
  name: '',
  desc: '',
  ...cloneDeep(datasetForm.value)
})

function closeConfirm (done: () => void) {
  if (isEqual({...datasetForm.value, ...BaseFormRef.value.form }, initFormData.value)) {
    return close(done)
  }
  MsgConfirm('提示', '修改后的信息未保存，确定不保存并关闭弹窗？').then(() => {
    close(done)
  })
}

function close (done: () => void) {
  isFunction(done) && done()
  dialogVisible.value = false
}
defineExpose({ open })

</script>
<style lang="scss" scope></style>
